package com.acwer.oa.web.api.controller;

import java.io.Console;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.acwer.dao.bus.ISqlMapper;
import com.acwer.dao.sys.SysMenuDao;
import com.acwer.dao.sys.SysRole2MenuDao;
import com.acwer.dao.sys.SysRoleDao;
import com.acwer.dao.sys.SysUserDao;
import com.acwer.domain.sys.DoublePansir;
import com.acwer.domain.sys.RpnMsg;
import com.acwer.domain.sys.SysMenu;
import com.acwer.domain.sys.SysRole;
import com.acwer.domain.sys.SysRole2Menu;
import com.acwer.domain.sys.SysUser;
import com.acwer.framework.common.FuncTwo;
import com.acwer.framework.data.DataRow;
import com.acwer.framework.data.DataTable;
import com.acwer.framework.data.TreeList;
import com.acwer.framework.data.TreeNode;
import com.acwer.framework.data.TreeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

@RestController
@RequestMapping("sys-set")
public class SysSettingController extends BaseController {

	/**
	 * 获取角色列表
	 */
	@Autowired
	SysRoleDao roleDao;

	@GetMapping("role")
	public RpnMsg role() {
		List<SysRole> roles = roleDao.selectList(null);
		FuncTwo<SysRole, String> pkFunc = (it) -> it.getId().toString();
		FuncTwo<SysRole, String> fkFun = (it) -> {
			return it.getPid() == null ? "" : it.getPid().toString();
		};
		TreeList<TreeNode<SysRole>> tree = TreeUtil.generTreeByParent(null, roles, pkFunc, fkFun);
		// DataTable<SysRole> table=new DataTable<SysRole>(roles,
		// SysRole.class);
		RpnMsg msg = SUCCESS();
		msg.setData(tree);
		return msg;
	}
	
	@GetMapping("rolels")
	public RpnMsg rolels() {
		List<SysRole> roles = roleDao.selectList(null);
		RpnMsg msg = SUCCESS();
		msg.setData(roles);
		return msg;
	}
	
	/**
	 * 获取编编辑的数据字典
	 * @return
	 */
	private  Map<String, DoublePansir> edmap() {
		Map<String, DoublePansir> map=new HashMap<String, DoublePansir>();
		map.put("sys_user", new DoublePansir<Class<?>,BaseMapper<?>>(){
			{
				setFirst(SysUser.class);
				setSecond(userDao);
			}
		});
		map.put("sys_menu", new DoublePansir(){
			{
				setFirst(SysMenu.class);
				setSecond(menuDao);
			}
		});
		
		map.put("sys_role", new DoublePansir(){
			{
				setFirst(SysRole.class);
				setSecond(roleDao);
			}
		});
		
		return map;
	}
	
	/**
	 * 通用编辑器-提交
	 * @param form
	 * @return
	 */
	@PostMapping("edrow")
	public RpnMsg edrow(@RequestBody Map<String, String> form){
		RpnMsg msg=SUCCESS();
		String tbName=form.get("tableName");
		String json=form.get("json");
		Map<String, DoublePansir> map=edmap();
		if(!map.containsKey(tbName)){
			msg=FAIL();
			msg.setMsg("没有相关映射表！");
			return msg;
		}
		DoublePansir pansir=map.get(tbName);
		Object obj=JSON.parseObject(json, (Class<?>)pansir.getFirst());
		BaseMapper mapper=(BaseMapper<?>)pansir.getSecond();
		int rows=mapper.updateById(obj);
		if(rows==0){
			mapper.insert(obj);
		}
		msg.setData(obj);
		return msg;
	}
	/**
	 * 获取数据行
	 * @return
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	@PostMapping("datarow")
	public RpnMsg DataRow(@RequestBody Map<String, String> form) throws Exception{
		RpnMsg msg=SUCCESS();
		String tableName=form.get("tableName");
		String id=form.get("id");
		
		Map<String, DoublePansir> map=edmap();
		
		if(!map.containsKey(tableName)){
			msg=FAIL();
			msg.setMsg("没有相关映射表！");
			return msg;
		}
		Class<?> clzz=(Class<?>)map.get(tableName).getFirst();
		Object obj=clzz.newInstance();
		BaseMapper<?> mapper=(BaseMapper<?>)map.get(tableName).getSecond();
		if(!StringUtils.isEmpty(id)){
			obj=mapper.selectById(id);
		}
		DataRow row=new DataRow(obj);
		msg.setData(row);
		
		return msg;
	}

	/**
	 * 删除表格数据
	 * @param form
	 * @return
	 */
	@PostMapping("destory")
	public RpnMsg destory(@RequestBody Map<String, String> form){
		RpnMsg msg=SUCCESS();
		
		String tableName=form.get("tableName");
		String ids=form.get("ids");
		
		Map<String, DoublePansir> map=edmap();
		
		if(!map.containsKey(tableName)){
			msg=FAIL();
			msg.setMsg("没有相关映射表！");
			return msg;
		}
		
		BaseMapper mapper=(BaseMapper<?>)map.get(tableName).getSecond();
		
		mapper.deleteBatchIds(Arrays.asList(ids.split(",")));
		
		return msg;
	}
	
	/**
	 * 获取所有用户
	 * 
	 * @return
	 */
	@PostMapping("users")
	public RpnMsg users(@RequestBody Map<String, String> form) {
		RpnMsg msg = SUCCESS();
		String s=form.get("s");
		List<SysUser> users = userDao.selectList(null);
		if(!StringUtils.isEmpty(s)){
			users=users.stream().filter(it->it.getName().contains(s)||
					it.getAccountId().contains(s)).collect(Collectors.toList());
		}
		DataTable<SysUser> table=new DataTable<SysUser>(users, SysUser.class);
		msg.setData(table);

		return msg;
	}

	/**
	 * 登录失败
	 */
	@Autowired
	SysUserDao userDao;

	@PostMapping("login")
	public RpnMsg login(@RequestBody Map<String, String> formData) {
		RpnMsg msg = SUCCESS();
		String username = formData.get("username");
		String password = formData.get("password");
		QueryWrapper<SysUser> userQuery = new QueryWrapper<SysUser>();
		userQuery.eq("account_id", username);
		userQuery.eq("password", password);
		SysUser user = userDao.selectOne(userQuery);
		// System.out.println(username);
		if (user != null) {
			JSONObject o = new JSONObject();
			o.put("accessToken", user.getAccountId());
			msg.setData(o);
		} else {
			msg = FAIL();
			msg.setMsg("登录失败，没找到相关帐户信息！");
		}
		return msg;
	}

	/**
	 * 获取菜单
	 */
	@Autowired
	SysMenuDao menuDao;

	@GetMapping("menu")
	public RpnMsg menu() {
		RpnMsg msg = SUCCESS();
		List<SysMenu> menus = menuDao.selectList(null);
		FuncTwo<SysMenu, String> pkFunc = (it) -> it.getId().toString();
		FuncTwo<SysMenu, String> fkFun = (it) -> {
			return it.getPid() == null ? "" : it.getPid().toString();
		};
		TreeList<TreeNode<SysMenu>> tree = TreeUtil.generTreeByParent(null, menus, pkFunc, fkFun);
		msg.setData(tree);
		return msg;
	}

	@Autowired
	SysRole2MenuDao role2MenuDao;

	/**
	 * 根据roleid获取菜单列表
	 * 
	 * @param ids
	 *            以英文逗号隔开
	 * @return
	 */
	@PostMapping("role2menuByIds")
	public RpnMsg Role2MenuByIds(@RequestBody Map<String, String> form) {
		String ids = form.get("ids");
		RpnMsg msg = SUCCESS();
		if (StringUtils.isEmpty(ids)) {
			msg = FAIL();
			msg.setMsg("role ids不能为空！");
		}

		List<String> idList = Arrays.asList(ids.split(","));

		List<SysMenu> menus = role2MenuDao.selectByRoleId(idList);

		FuncTwo<SysMenu, String> pkFunc = (it) -> it.getId().toString();
		FuncTwo<SysMenu, String> fkFun = (it) -> {
			return it.getPid() == null ? "" : it.getPid().toString();
		};
		TreeList<TreeNode<SysMenu>> tree = TreeUtil.generTreeByParent(null, menus, pkFunc, fkFun);

		msg.setData(tree);

		return msg;
	}

	@Autowired
	ISqlMapper sqlDao;
	/**
	 * 保存权限
	 * @param ls
	 * @return
	 */
	@PostMapping("saveRole2Menu")
	public RpnMsg saveRole2Menu(@RequestBody List<SysRole2Menu> ls){
		RpnMsg msg=SUCCESS();
		String roleid="-1";
		for (SysRole2Menu sysRole2Menu : ls) {
			roleid=sysRole2Menu.getRoleid();
		}
		if(!roleid.equals("-1")){
			sqlDao.delete("delete from sys_role2menu where roleid='"+roleid+"'");
		}
		for (SysRole2Menu r2m : ls) {
			role2MenuDao.insert(r2m);
		}
		return msg;
	}
	
//	
	/**
	 * 合并查询，查询出菜单及角色的权限
	 * 
	 * @param form
	 *            roleid 角色id
	 * @return
	 */
	@PostMapping("selectByRole2Menu")
	public RpnMsg selectByRole2Menu(@RequestBody Map<String, String> form) {
		RpnMsg msg = SUCCESS();
		String roleid=form.get("roleid");
		List<SysMenu> menus = role2MenuDao.selectByRole2Menu(roleid);
		FuncTwo<SysMenu, String> pkFunc = (it) -> it.getId().toString();
		FuncTwo<SysMenu, String> fkFun = (it) -> {
			return it.getPid() == null ? "" : it.getPid().toString();
		};
		TreeList<TreeNode<SysMenu>> tree = TreeUtil.generTreeByParent(null, menus, pkFunc, fkFun);
		msg.setData(tree);
		return msg;
	}

	/**
	 * 根据帐号ID获取用户信息
	 * 
	 * @param formData
	 * @return
	 */
	@PostMapping("uinfo")
	public RpnMsg uinfo(@RequestBody Map<String, String> formData, HttpServletRequest request) {
		RpnMsg msg = SUCCESS();
		String accountId = request.getAttribute("account").toString();
		QueryWrapper<SysUser> userQuery = new QueryWrapper<SysUser>();
		userQuery.eq("account_id", accountId);

		SysUser user = userDao.selectOne(userQuery);
		JSONObject o = new JSONObject();
		o.put("user", user);
		msg.setData(o);
		// accountId
		return msg;
	}
}
